package com.hroay.netty02.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * @author heyingcheng
 * @category Class description
 * @email heyingcheng@ctvit.com.cn
 * @date 2018/2/1 16:54
 */
@Slf4j
public class TimeClient {

    private String ip;

    private int port;

    private Socket socket;

    public TimeClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void connect() {
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));){
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String command = scanner.next();
                writer.write(command);
                writer.newLine();
                writer.flush();
                String response = reader.readLine();
                log.info(response);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        TimeClient timeClient = new TimeClient("127.0.0.1", 9999);
        timeClient.connect();
    }

}
